package com.originskyseed.platform.count.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.util.DataUtil;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.count.i18n.CountResponseMsg;
import com.originskyseed.platform.count.service.ICountVideoEarningsService;
import com.originskyseed.platform.count.vo.CountVideoEarningsVO;
import com.originskyseed.platform.count.vo.request.CountVideoEarningsRequestVO;
import com.originskyseed.platform.user.model.Family;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IFamilyService;

/**
 * Controller类（OSI_ANCHOR_EARNINGS）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/countVideoEarnings")
@BaseLocaleResource(localeFileName = "i18n_count")
public class CountVideoEarningsController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CountVideoEarningsController.class);

	@DubboReference
	private ICountVideoEarningsService countVideoEarningsVOService;

	@DubboReference
	private IFamilyService familyService;

	/**
	 * 收益时间查询列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/countVideoEarningsTimeList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CountVideoEarningsVO>> countVideoEarningsTimeList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CountVideoEarningsVO>> result = null;
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// Family family = this.familyService.selectByUserId(userInfo.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			/*
			 * if(family != null){ requestVO.setFamilyId(family.getFamilyId()); }
			 */
			// 默认赋值自然日前两周时间
			if (requestVO.getStartDate() == null && requestVO.getEndDate() == null) {
				requestVO.setStartDate(sdf.format(DataUtil.getLastWeekDateFirstDayOrBeforeLastFirstDay(new Date())));
				requestVO.setEndDate(sdf.format(new Date()));
			}
			// 分页查询
			BasePage<CountVideoEarningsVO> page = new BasePage<CountVideoEarningsVO>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.countVideoEarningsVOService.selectByTimeEarningsList(requestVO.toMap(), page, userInfo);
			result = new BaseResponseBody<BasePage<CountVideoEarningsVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.VIDEO_EARNINGS_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CountVideoEarningsVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.VIDEO_EARNINGS_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 主播收益查询列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/countAnchorEarningsList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CountVideoEarningsVO>> countAnchorEarningsList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CountVideoEarningsVO>> result = null;
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			// 1日报 2月报
			Integer type = this.getParameterInteger("type", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// Family family = this.familyService.selectByUserId(userInfo.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			/*
			 * if(family != null){ requestVO.setFamilyId(family.getFamilyId()); }
			 */
			if (type != null) {
				if (type == 1) {
					requestVO.setStartDate(sdf.format(new Date()));
					requestVO.setEndDate(sdf.format(new Date()));
				}
				if (type == 2) {
					requestVO.setStartDate(sdf.format(DataUtil.getCurrentMonthDateBegin(new Date())));
					requestVO.setEndDate(sdf.format(new Date()));
				}
			}
			// 分页查询
			BasePage<CountVideoEarningsVO> page = new BasePage<CountVideoEarningsVO>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.countVideoEarningsVOService.countAnchorEarningsList(requestVO.toMap(), page, userInfo);
			result = new BaseResponseBody<BasePage<CountVideoEarningsVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ANCHOR_DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CountVideoEarningsVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ANCHOR_DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 频道收益查询列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/countChannelEarningsList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CountVideoEarningsVO>> countChannelEarningsList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CountVideoEarningsVO>> result = null;
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			// 1日报 2月报
			Integer type = this.getParameterInteger("type", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// Family family = this.familyService.selectByUserId(userInfo.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			/*
			 * if(family != null){ requestVO.setFamilyId(family.getFamilyId()); }
			 */
			if (type != null) {
				if (type == 1) {
					requestVO.setStartDate(sdf.format(new Date()));
					requestVO.setEndDate(sdf.format(new Date()));
				}
				if (type == 2) {
					requestVO.setStartDate(sdf.format(DataUtil.getCurrentMonthDateBegin(new Date())));
					requestVO.setEndDate(sdf.format(new Date()));
				}
			}
			// 分页查询
			BasePage<CountVideoEarningsVO> page = new BasePage<CountVideoEarningsVO>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.countVideoEarningsVOService.countChannelEarningsList(requestVO.toMap(), page, userInfo);
			result = new BaseResponseBody<BasePage<CountVideoEarningsVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.CHANNEL_INFO_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CountVideoEarningsVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.CHANNEL_INFO_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 选择家族下的主播信息列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectAnchorInfoList.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody selectAnchorInfoList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Family family = this.familyService.selectByUserId(userInfo.getId());
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
			}
			List<CountVideoEarningsVO> list = this.countVideoEarningsVOService.selectAnchorInfoOnFamilyList(requestVO.toMap());
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ANCHOR_INFO_LIST_SUCCESS.getMsg()), list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.ANCHOR_INFO_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 选择家族下的频道信息列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectChannelInfoList.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody selectChannelInfoList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Family family = this.familyService.selectByUserId(userInfo.getId());
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
			}
			List<CountVideoEarningsVO> list = null; // this.countVideoEarningsVOService.selectChannelInfoOnFamilyList(requestVO.toMap());
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.CHANNEL_INFO_LIST_SUCCESS.getMsg()), list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.CHANNEL_INFO_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 频道收益列表导出Excel
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/channelEarningsToExcel.json")
	@SysLog(module = "频道收益模块", operationDesc = "频道收益列表信息")
	public void channelEarningsToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			// 1日报 2月报
			Integer type = this.getParameterInteger("type", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<CountVideoEarningsVO> list = null;
			Family family = this.familyService.selectByUserId(userInfo.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
			}
			if (type != null) {
				if (type == 1) {
					requestVO.setStartDate(sdf.format(new Date()));
					requestVO.setEndDate(sdf.format(new Date()));
				}
				if (type == 2) {
					requestVO.setStartDate(sdf.format(DataUtil.getCurrentMonthDateBegin(new Date())));
					requestVO.setEndDate(sdf.format(new Date()));
				}
			}
			list = this.countVideoEarningsVOService.countChannelEarningsListToExcel(requestVO.toMap());
			// excel标题
			String[] title = { "频道ID", "频道名称", "开始时间", "结束时间", "累计时长", "观看人数", "公会房间开播流水（元）" };
			// excel文件名
			String fileName = "频道收益列表信息.xls";
			// sheet名
			String sheetName = "频道收益信息";
			String[][] values = new String[list.size()][];
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					CountVideoEarningsVO obj = list.get(i);
					values[i][0] = obj.getChannelId();
					values[i][1] = obj.getChannelName();
					values[i][2] = format.format(obj.getStartTime());
					values[i][3] = format.format(obj.getEndTime());
					values[i][4] = obj.getAllLiveTime();
					values[i][5] = obj.getViewPlayers().toString();
					values[i][6] = obj.getTradeUnionAccount().toString();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 主播收益列表导出Excel
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/anchorEarningsToExcel.json")
	@SysLog(module = "主播收益模块", operationDesc = "主播收益列表信息")
	public void anchorEarningsToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 1日报 2月报
			Integer type = this.getParameterInteger("type", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<CountVideoEarningsVO> list = null;
			Family family = this.familyService.selectByUserId(userInfo.getId());
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
			}
			if (type != null) {
				if (type == 1) {
					requestVO.setStartDate(sdf.format(new Date()));
					requestVO.setEndDate(sdf.format(new Date()));
				}
				if (type == 2) {
					requestVO.setStartDate(sdf.format(DataUtil.getCurrentMonthDateBegin(new Date())));
					requestVO.setEndDate(sdf.format(new Date()));
				}
			}
			list = this.countVideoEarningsVOService.countAnchorEarningsListToExcel(requestVO.toMap(), userInfo);
			// excel标题
			String[] title = { "主播ID", "主播昵称", "开始时间", "结束时间", "累计时长", "观看人数", "个人房间开播流水（元）", "公会房间开播流水（元）", "主播流水（元）", "家族收益（元）" };
			// excel文件名
			String fileName = "主播收益列表信息.xls";
			// sheet名
			String sheetName = "主播收益信息";
			String[][] values = new String[list.size()][];
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					CountVideoEarningsVO obj = list.get(i);
					values[i][0] = obj.getAnchorId();
					values[i][1] = obj.getNickName();
					values[i][2] = format.format(obj.getStartTime());
					values[i][3] = format.format(obj.getEndTime());
					values[i][4] = obj.getAllLiveTime();
					values[i][5] = obj.getViewPlayers().toString();
					values[i][6] = obj.getPersonAccount().toString();
					values[i][7] = obj.getTradeUnionAccount().toString();
					values[i][8] = obj.getAnchorAccount().toString();
					values[i][9] = obj.getFamilyEarnings().toString();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 收益时间列表导出Excel
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/exportToExcel.json")
	@SysLog(module = "直播收益模块", operationDesc = "收益时间列表信息")
	public void exportToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			CountVideoEarningsRequestVO requestVO = this.getParameterBean(CountVideoEarningsRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<CountVideoEarningsVO> list = null;
			Family family = this.familyService.selectByUserId(userInfo.getId());
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
			}
			list = this.countVideoEarningsVOService.selectByTimeEarningsListToExcel(requestVO.toMap(), userInfo);
			// excel标题
			String[] title = { "主播ID", "主播昵称", "开播总时长", "个人直播时长", "公会排麦时长", "开播有效天", "个人房间开播流水（元）", "公会房间开播流水（元）", "主播流水（元）", "家族收益（元）" };
			// excel文件名
			String fileName = "收益时间列表信息.xls";
			// sheet名
			String sheetName = "收益时间信息";
			String[][] values = new String[list.size()][];

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					CountVideoEarningsVO obj = list.get(i);
					values[i][0] = obj.getAnchorId();
					values[i][1] = obj.getNickName();
					values[i][2] = obj.getAllLiveTime() == null ? "" : obj.getAllLiveTime();
					values[i][3] = obj.getPersonLiveTime() == null ? "" : obj.getPersonLiveTime();
					values[i][4] = obj.getTradeUnionLiveTime() == null ? "" : obj.getTradeUnionLiveTime();
					values[i][5] = obj.getWorkDay() == null ? "" : obj.getWorkDay().toString();
					values[i][6] = obj.getPersonAccount().toString();
					values[i][7] = obj.getTradeUnionAccount().toString();
					values[i][8] = obj.getAnchorAccount().toString();
					values[i][9] = obj.getFamilyEarnings() == null ? "0" : obj.getFamilyEarnings().toString();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

}
